//
//  HTTPClient.swift
//  httpObj
//
//  Created by bianruifeng on 2017/7/23.
//  Copyright © 2017年 bianruifeng. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON
/// 请求响应状态
///
/// - success: 响应成功
/// - unusual: 响应异常
/// - failure: 请求错误
enum ResponseStatus: Int {
    case success  = 0
    case unusual  = 1
    case failure  = 3
}



/// 网络请求回调闭包 status:响应状态 result:JSON tipString:提示给用户的信息
typealias NetworkFinished = ( _ status: ResponseStatus, _ result: JSON?, _ tipString: String?) -> ()



class HTTPClient: NSObject {

    /// 网络工具类单例
    static let shared = HTTPClient()
    
    var rootDomain: String {
        #if DEBUG
            return ""
        #else
            return ""
        #endif
    }
    

    
}



extension HTTPClient{
    
    
    // --GET请求获取JSON数据
    class func GET(URLString: String, parameters: [String: Any]?, successed:@escaping (_ responseObject: AnyObject) -> (), failed: @escaping (_ error: NSError?) -> ()){
        
        Alamofire.request(URLString,method:.get,parameters:parameters).validate().responseJSON { response in
            switch response.result {
            case .success(let value):
                print(value)
                print(response)
                print("Validation Successful")
                let json = JSON(value)
//                let jsonStr = json
                print(json["msg"])
                print("JSON: \(json)")
                successed(response.result as AnyObject);
            case .failure(let error):
                print(error)
                failed(error as NSError);
            }
        }
        
    }
    
    /**
     GET请求
     
     - parameter URLString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func get(_ APIString: String, parameters: [String : Any]?, needHeaders: Bool = true, needLoading: Bool = false, finished: @escaping NetworkFinished) {
        
        if needLoading {
            //            HexaLoading.show(in: UIApplication.shared.keyWindow!)
        }
        
        let headers = needHeaders ? self.headers() : nil
        
        
        Alamofire.request(rootDomain + APIString, method: .get, parameters: parameters, headers: headers).responseJSON { (response) in
            self.handle(response: response, finished: finished, needLoading: needLoading)
        }
        
        
    }
    
    
    
    // --POST请求获取JSON数据
    func POST(URLString: String, parameters: AnyObject, successed:(_ responseObject: AnyObject?) -> (), failed: (_ error: NSError?) -> ()) {
        
        Alamofire.request("http://httpbin.org/post", method: .post, parameters: ["name": "JackieQu"]).responseJSON { (response) in
            guard let result =  response.result.value else {
                print(response.result.error!)
                return
            }
            
            print(result)
        }
        
        
    }
    
    /**
     POST请求
     
     - parameter URLString:  urlString
     - parameter parameters: 参数
     - parameter finished:   完成回调
     */
    func post(_ APIString: String, parameters: [String : Any]?, needHeaders: Bool = true, needLoading: Bool = false, finished: @escaping NetworkFinished) {
        
        
        if needLoading {
//            HexaLoading.show()
        }
        
        let headers = needHeaders ? self.headers() : nil
        
//        DLog("\n🌎🌎🌎\nRequest: \nURL: \(rootDomain + APIString)\nMethod: post\nHeaders:\(String(describing: headers))\nParameters: \(String(describing: parameters))\n🌎🌎🌎")
        
        Alamofire.request(rootDomain + APIString, method: .post, parameters: parameters, headers: headers).responseJSON { (response) in
            self.handle(response: response, finished: finished, needLoading: needLoading)
        }
    }
    

    
    /// 处理响应结果
    ///
    /// - Parameters:
    ///   - response: 响应对象
    ///   - finished: 完成回调
    fileprivate func handle(response: DataResponse<Any>, finished: @escaping NetworkFinished, needLoading: Bool) {
        
        if needLoading {
            
        }
        
        switch response.result {
        case .success(let value):
            let json = JSON(value)
            
            if json["code"].string == "OK" {
                finished(.success, json, json["message"].string)
            } else {
                finished(.unusual, json, json["message"].string)
            }
        case .failure(let error):
            
            finished(.failure, nil, error.localizedDescription)
        }
    }
    
    
    
    /// 获取请求头
    ///
    /// - Returns: 字典-请求头内容
    fileprivate func headers() -> Dictionary<String, String>! {
        
        let acceptLanguage = Locale.preferredLanguages
            .prefix(6)
            .enumerated()
            .map { index, languageCode in
                let quality = 1.0 - (Double(index) * 0.1)
                return "\(languageCode),q=\(quality)"
            }
            .joined(separator: ", ")
        
        let userAgent: String = {
            if let info = Bundle.main.infoDictionary {
                return "HEXA/iOS/" + (info["CFBundleShortVersionString"] as? String ?? "Unknown")
            }
            return "HEXA/iOS/Unknown"
        }()
        
        return [
            "Accept-Encoding": "gzip;q=1.0, compress;q=0.5",
            "Accept-Language": acceptLanguage,
            "User-Agent": userAgent,
            
            "X-App-OSVersion": UIDevice().systemVersion,
            "X-App-Device": UIDevice().localizedModel,
            "X-User-AccessToken": UserDefaults.standard.string(forKey: "ACCESSTOKEN_KEY") ?? ""
        ]
    }
    
    

}
